<?php

namespace PHPSpring\Type;

class Datetime implements \JsonSerializable {

  private ?\DateTime $dateTime = null;
  private bool $empty = false;
  private static string $format = 'Y-m-d H:i:s';


  public function __construct ($datetime = null) {
    if (empty($datetime)) {
      $this->empty = true;
    } elseif ($datetime instanceof \DateTime) {
      $this->dateTime = $datetime;
    } elseif (is_string($datetime)) {
      if (strpos($datetime, '0000-') === 0) {
        $this->empty = true;
      } else {
        $this->dateTime = new \DateTime($datetime);
      }
    } else {
      $this->dateTime = new \DateTime($datetime);
    }
  }

  public static function setFormat (string $format = 'Y-m-d H:i:s') {
    self::$format = $format;
  }

  public function jsonSerialize () {
    return $this->format(self::$format);
  }

  public function format ($format = 'Y-m-d H:i:s'): string {
    if (empty($this->dateTime)) {
      return '0';
    }

    return $this->dateTime->format($format);
  }

  public function empty (): bool {
    return $this->empty;
  }

  /**
   * Check empty() first!
   * @return \DateTime|null
   */
  public function &get () {
    return $this->dateTime;
  }

  public function __toString () {
    return $this->format(self::$format);
  }

}
